﻿using AutoMapper;
using DocumentFormat.OpenXml.Drawing.Charts;
using Domain.InvoiceTicket.Invoicing;
using Domain.InvoiceTicket.Ticket;
using Domain.Process_Procedures;
using Domain.Production_Modules;
using Infratructure.Interface;
using MediatR;
using MES.Server.API.Application.Command.InvoiceTicket.Invoice;
using MES.Server.API.Application.Command.InvoiceTicket.Ticket;
using MES.Server.API.Application.Command.Process_Procedures.ProcessFlow;
using ReturnValue;
using System.Diagnostics;
using System.Transactions;
using Yitter.IdGenerator;

namespace MES.Server.API.Application.Handler.InvoiceTicket.Invoice
{

    /// <summary>
    /// 到票添加
    /// </summary>
    public class InvoiceCreateCommandHandler : IRequestHandler<InvoiceCreateCommand, ApiResult<int>>
    {
        
        /// <summary>
        /// 到票表
        /// </summary>
        private readonly IRepository<InvoicingModel> _processFlowRepo;
        /// <summary>
        /// 订单表
        /// </summary>
        private readonly IRepository<OrderModel> _processMqRepo;
        /// <summary>
        /// 到票订单表
        /// </summary>
        private readonly IRepository<InvoicingorderModel> processFlowDetailRepo;
        private readonly IMapper _mapper;
        private readonly ILogger<InvoiceCreateCommandHandler> _logger;

        /// <summary>
        /// 注入所需仓储
        /// </summary>
        public InvoiceCreateCommandHandler(IRepository<InvoicingModel> processFlowRepo, IRepository<OrderModel> processMqRepo,
            IRepository<InvoicingorderModel> processFlowDetailRepo,
            IMapper mapper,
            ILogger<InvoiceCreateCommandHandler> logger)
        {
            _processFlowRepo = processFlowRepo;
            _processMqRepo = processMqRepo;
            this.processFlowDetailRepo = processFlowDetailRepo;
            _mapper = mapper;
            _logger = logger;

        }


        public async Task<ApiResult<int>> Handle(InvoiceCreateCommand request, CancellationToken cancellationToken)
        {
            // 这里不再创建新订单，而是直接使用请求中的订单ID
            // 假设 request.Procedures 中包含了要关联的订单ID

            var processFlow = _mapper.Map<InvoicingModel>(request);
            processFlow.Id = YitIdHelper.NextId();
            processFlow.CreateTime = DateTime.Now;
            processFlow.UpdaterPeople = "admin";

            var r2 = 0;
            var r3 = 0;
            using (var tran = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                try
                {
                    // 添加到票
                    r2 = await _processFlowRepo.AddAsync(processFlow);

                    // 创建中间表关联数据
                    var flowDetails = request.Procedures.Select(p => new InvoicingorderModel
                    {
                        Id = YitIdHelper.NextId(),
                        InvoicingId = processFlow.Id,
                        OrderId = p.Id // 使用选择的订单ID
                    }).ToList();

                    r3 = await processFlowDetailRepo.CreateRangeAsync(flowDetails);

                    tran.Complete();
                }
                catch (Exception ex)
                {
                    _logger.LogError($"发生异常，事务回滚：{ex.Message}");
                    throw;
                }
            }

            if (r2 > 0 && r3 > 0)
            {
                return new ApiResult<int>().Success("保存成功！", r2 + r3);
            }
            else
            {
                return new ApiResult<int>().Fail("保存失败！");
            }

        }
    }
}
    
